package com.ag.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * title: MavenUtils.java 
 * Maven 项目拷贝到另一个项目
 *
 * @author rplees
 * @email rplees.i.ly@gmail.com
 * @version 1.0  
 * @created Nov 8, 2019 9:26:11 PM
 */
public class MavenUtils {
	
	public static void main(String[] args) throws Exception {
		final String sourceKey = "ybm";
		final String targetKey = "manshiguang";
		
		final String baseDir = "/Users/rplees/work/git";
		final String sourceMavenProject = sourceKey + "-parent";
		final String targetMavenProject = targetKey + "-parent";
		
		File sourceDic = new File(FileUtils.splicePaths(baseDir, sourceMavenProject));
		File targetDic = new File(FileUtils.splicePaths(baseDir, targetMavenProject));
		
		if(! targetDic.exists()) { //copy
			org.apache.commons.io.FileUtils.copyDirectory(sourceDic, targetDic);
			org.apache.commons.io.FileUtils.deleteDirectory(new File(FileUtils.splicePaths(targetDic.getPath(), ".git")));
		}
		
		遍历文件(targetDic, sourceKey, targetKey, 0);
	}

	static void 遍历文件(File targetDic, String sourceKey, String targetKey, int level) {
		Arrays.asList(targetDic.listFiles()).forEach(f -> {
			if(f.isDirectory()) {
				File f0 = f;
				if(/**level == 0 && */StringUtils.isNotBlank(f.getName()) && StringUtils.lastIndexOf(f.getName(), sourceKey) > -1) {
					File newFile = new File(StringUtils.replace(f.getAbsolutePath(), sourceKey, targetKey));
					f.renameTo(newFile);
					f0 = newFile;
				}
				
				遍历文件(f0, sourceKey, targetKey, level + 1);
				return;
			}
			
			//.project //.pom.xml
			if(StringUtils.isNotBlank(f.getName()) && StringUtils.lastIndexOf(f.getName(), ".project") > -1
					|| StringUtils.isNotBlank(f.getName()) && StringUtils.lastIndexOf(f.getName(), "pom.xml") > -1) {
				indexOfDo(f, sourceKey, targetKey);
			}
			
			//,java
			if(StringUtils.isNotBlank(f.getName()) && StringUtils.lastIndexOf(f.getName(), ".java") > -1) {
				indexOfDo(f, "com." + sourceKey, "com." + targetKey);
			}
		});
	}
	
	static void indexOfDo(File f, String source, String target) {
		AtomicBoolean isChange = new AtomicBoolean(false);
		try {
			List<String> targetConents = new ArrayList<>();
			Files.readAllLines(f.toPath(), StandardCharsets.UTF_8).forEach(text -> {
				isChange.set(true);
				if (StringUtils.indexOf(text, source) > -1) {
					targetConents.add(StringUtils.replace(text, source, target));
				} else {
					targetConents.add(text);
				}
			});
			
			// 替换
			if(isChange.get())
				Files.write(f.toPath(), targetConents, StandardOpenOption.TRUNCATE_EXISTING);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
